class Solution(object):
    def canFinish(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: bool
        """
        pres = [set() for _ in range(numCourses)]
        for course, pre in prerequisites:
            pres[course].add(pre)
        # check loop
        already = [False] * numCourses
        request = set()
        class LoopException(Exception):
            pass
        def find(course):
            if already[course]: return
            if course in request: raise LoopException() 
            request.add(course)
            for pre in pres[course]:
                if not already[pre]:
                    find(pre)
            request.remove(course)
            already[course] = True
        for course in range(numCourses):
            try:
                find(course)
            except LoopException:
                return False
        return True

print(Solution().canFinish(2, [[1,0]]))